import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { login, logout, getUserInfo } from '@/api/auth'
import router from '@/router'

export interface UserInfo {
  id: number;
  username: string;
  nickname: string;
  email: string;
  phone: string;
  departmentId: number;
  departmentName: string;
  roles: string[];
  permissions: string[];
}

export const useUserStore = defineStore('user', () => {
  // 状态
  const token = ref<string>(localStorage.getItem('token') || '')
  const userInfo = ref<UserInfo | null>(null)

  // 计算属性
  const isAuthenticated = computed(() => !!token.value)
  
  // 判断是否有任一角色权限
  const hasAnyRole = (roles: string[]) => {
    if (!userInfo.value || !userInfo.value.roles) return false
    return roles.some(role => userInfo.value!.roles.includes(role))
  }
  
  // 判断是否有权限
  const hasPermission = (permission: string) => {
    if (!userInfo.value || !userInfo.value.permissions) return false
    return userInfo.value.permissions.includes(permission)
  }

  // 登录操作
  const loginAction = async (username: string, password: string) => {
    try {
      const res = await login(username, password)
      token.value = res.data
      localStorage.setItem('token', res.data)
      await fetchUserInfo()
      return Promise.resolve(true)
    } catch (error) {
      return Promise.reject(error)
    }
  }
  
  // 登出操作
  const logoutAction = async () => {
    try {
      await logout()
      resetState()
      router.push('/login')
      return Promise.resolve(true)
    } catch (error) {
      return Promise.reject(error)
    }
  }
  
  // 获取用户信息
  const fetchUserInfo = async () => {
    try {
      const res = await getUserInfo()
      userInfo.value = res.data
      return Promise.resolve(res.data)
    } catch (error) {
      return Promise.reject(error)
    }
  }
  
  // 重置状态
  const resetState = () => {
    token.value = ''
    userInfo.value = null
    localStorage.removeItem('token')
  }

  return {
    token,
    userInfo,
    isAuthenticated,
    hasAnyRole,
    hasPermission,
    loginAction,
    logoutAction,
    fetchUserInfo,
    resetState
  }
}) 